import {
    Action
} from 'redux';

import userEach from './../../utils/userEach';

import * as types from './../types/connection';
import * as commonTypes from './../types/common';

interface State {
    [orderBy: number]: Array<any>
}

const initState = {} as State;

interface _Action extends Action{
    data:any
}

export default (state = initState, action: _Action) => {
    const {
        type,
        data
    } = action;

    switch (type) {

        case types.getConnectionList: {
            const {
                isPush,
                orderBy,
                queryList,
                userId = 0
            } = data;

            const _key = (
                `${orderBy}_${userId}` as never
            );

            if (!isPush) {
                state[_key] = queryList;
            }
            else {
                const _list = state[_key] || [];
                state[_key] = [..._list, ...queryList];
            }
            return {
                ...state
            }
        }

        case commonTypes.postLikeUser: {
            const {
                userId,
                logUserId = 0
            } = data;

            return userEach(
                state,
                userId,
                logUserId,
                (item:any) => {
                    item.isLiked = 1;
                    item.likeTotal += 1;
                })
        }

        case commonTypes.resetLikeUser: {
            const {
                userId,
                logUserId = 0
            } = data;

            return userEach(
                state,
                userId,
                logUserId,
                (item:any) => {
                    item.isLiked = 0;
                    item.likeTotal += -1;
                })
        }

        case commonTypes.blockUser: {
            const {
                userId,
                logUserId = 0
            } = data;
            return userEach(
                state,
                userId,
                logUserId,
                (item:any) => {
                    item.isBlocked = true;
                })
        }
    }
    return state;
}